<?php
/**
 * Guard 辅助方法
 *
 * Author: Zeon
 * Date: 2017/11/14
 * Time: 17:19
 * Created by PhpStorm.
 */
namespace App\Services\Utils;


use App\Models\Admin;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Tymon\JWTAuth\JWTAuth;
use Tymon\JWTAuth\JWTGuard;

class Guard
{
    /**
     * Delegate Gate Method On Auth::guard
     * @example
     *      Guard::matchId($admin_model, $operate_model)
     *
     * @param  string  $method
     * @param  mixed[2]  $parameters
     * @return mixed
     */
    public static function __callStatic($method, array $parameters)
    {
        list($admin, $arguments) = $parameters;

        return Gate::forUser($admin)->check($method, $arguments);
    }

    /**
     * @param $user
     *
     * @return string - token
     */
    public static function JWTUserLogin(User $user): string
    {
        return self::JWTLogin($user, User::GUARD_NAME);
    }

    /**
     * @param $user
     *
     * @return string - token
     */
    public static function JWTAdminLogin(Admin $user): string
    {
        return self::JWTLogin($user, Admin::GUARD_NAME);
    }

    /**
     * @param JWTSubject $user
     *
     * @param string $guard_name
     *
     * @return string - token
     */
    public static function JWTLogin(JWTSubject $user,
                                    string $guard_name): string
    {
        /** @var JWTAuth|JWTGuard $guard */
        $guard = Auth::guard($guard_name);

        $token = $guard->login($user);

        return $token;
    }

    public static function user(): ?User
    {
        return Auth::guard(User::GUARD_NAME)->user();
    }

    public static function admin(): ?Admin
    {
        return Auth::guard(Admin::GUARD_NAME)->user();
    }
}